import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../components"

/**
 * 总览页面
 * 显示3个配电室的总体状态
 * 
 * 布局优化（1024×768分辨率）：
 * - 可用区域：794px宽 × 738px高
 * - 页面标题：30px（压缩）
 * - 配电室卡片：140px（压缩，3列横向）
 * - 系统统计：80px（压缩）
 * - 电表列表：剩余空间（约460px，最大化）
 * - 主间距：10px × 4 = 40px
 */
Item {
    id: root

    // 刷新定时器
    Timer {
        id: refreshTimer
        interval: 1000 // 每秒刷新一次
        running: true
        repeat: true
        onTriggered: {
            updateDashboard()
        }
    }

    // 主布局
    ColumnLayout {
        anchors.fill: parent
        spacing: 10

        // 页面标题（压缩到30px）
        Text {
            text: "📊 系统总览"
            font.pixelSize: 16
            font.bold: true
            color: "#2c3e50"
            Layout.preferredHeight: 30
        }

        // 配电室统计卡片（压缩到140px）
        GridLayout {
            Layout.fillWidth: true
            columns: 3
            rowSpacing: 10
            columnSpacing: 10

            // 配电室A（压缩到140px）
            Rectangle {
                id: roomACard
                Layout.fillWidth: true
                Layout.preferredHeight: 140

                property string roomName: "配电室A"
                property int roomId: 1
                property string busIcon: "🏢"
                property int totalMeters: 40
                property int startMeterId: 1
                property int endMeterId: 40
                property int onlineMeters: 0
                property real totalPower: 0
                property real totalCurrent: 0

                radius: 6
                color: "white"
                border.width: 2
                border.color: "#3498db"

                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    cursorShape: Qt.PointingHandCursor

                    onEntered: {
                        roomACard.scale = 1.02
                    }

                    onExited: {
                        roomACard.scale = 1.0
                    }

                    onClicked: {
                        console.log("Clicked distribution room:", roomACard.roomName) // 打印点击的配电室名称
                        // 切换到电表列表页并筛选配电室A
                        mainWindow.switchPage("meterlist")
                        // 通过全局属性或信号通知MeterListPage设置筛选条件
                        if (meterModel) {
                            meterModel.filterMode = 3  // ShowByBus
                            meterModel.filterBusId = roomACard.roomId
                            meterModel.refresh()
                        }
                    }
                }

                Behavior on scale {
                    NumberAnimation {
                        duration: 200
                        easing.type: Easing.OutCubic
                    }
                }

                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: 12
                    spacing: 6

                    RowLayout {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 24
                        spacing: 8

                        Text {
                            text: roomACard.busIcon
                            font.pixelSize: 16
                        }

                        Text {
                            text: roomACard.roomName
                            font.pixelSize: 13
                            font.bold: true
                            color: "#2c3e50"
                            Layout.fillWidth: true
                        }

                        Rectangle {
                            width: 45
                            height: 22
                            radius: 3
                            color: roomACard.onlineMeters > 0 ? "#27ae60" : "#e74c3c"

                            Text {
                                anchors.centerIn: parent
                                text: roomACard.onlineMeters > 0 ? "运行" : "离线"
                                font.pixelSize: 10
                                font.bold: true
                                color: "white"
                            }
                        }
                    }

                    Rectangle {
                        Layout.fillWidth: true
                        height: 1
                        color: "#ecf0f1"
                    }

                    GridLayout {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        columns: 2
                        rowSpacing: 6
                        columnSpacing: 10

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "在线设备"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: roomACard.onlineMeters + "/" + roomACard.totalMeters
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#27ae60"
                                }

                                Text {
                                    text: "台"
                                    font.pixelSize: 10
                                    color: "#95a5a6"
                                }
                            }
                        }

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "在线率"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: roomACard.totalMeters > 0 ? Math.round((roomACard.onlineMeters / roomACard.totalMeters) * 100) : 0
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#3498db"
                                }

                                Text {
                                    text: "%"
                                    font.pixelSize: 10
                                    color: "#95a5a6"
                                }
                            }
                        }

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "总功率"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: (roomACard.totalPower / 1000).toFixed(1)
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#9b59b6"
                                }

                                Text {
                                    text: "kW"
                                    font.pixelSize: 10
                                    color: "#95a5a6"
                                }
                            }
                        }

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "总电流"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: roomACard.totalCurrent.toFixed(1)
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#f39c12"
                                }

                                Text {
                                    text: "A"
                                    font.pixelSize: 10
                                    color: "#95a5a6"
                                }
                            }
                        }
                    }
                }

                function updateData() {
                    if (!deviceManager) {
                        console.warn("DashboardPage: deviceManager is null")
                        return
                    }

                    try {
                        roomACard.onlineMeters = deviceManager.getOnlineCountByBus(roomACard.roomId)
                        roomACard.totalPower = deviceManager.getTotalPowerByBus(roomACard.roomId)
                        roomACard.totalCurrent = deviceManager.getTotalCurrentByBus(roomACard.roomId)
                    } catch (e) {
                        console.error("DashboardPage: Error updating room A data:", e)
                    }
                }
            }

            // 配电室B（压缩到140px）
            Rectangle {
                id: roomBCard
                Layout.fillWidth: true
                Layout.preferredHeight: 140

                property string roomName: "配电室B"
                property int roomId: 2
                property string busIcon: "🏭"
                property int totalMeters: 40
                property int startMeterId: 41
                property int endMeterId: 80
                property int onlineMeters: 0
                property real totalPower: 0
                property real totalCurrent: 0

                radius: 6
                color: "white"
                border.width: 2
                border.color: "#3498db"

                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    cursorShape: Qt.PointingHandCursor

                    onEntered: {
                        roomBCard.scale = 1.02
                    }

                    onExited: {
                        roomBCard.scale = 1.0
                    }

                    onClicked: {
                        console.log("Clicked distribution room:", roomBCard.roomName)
                        // 切换到电表列表页并筛选配电室B
                        mainWindow.switchPage("meterlist")
                        // 通过全局属性或信号通知MeterListPage设置筛选条件
                        if (meterModel) {
                            meterModel.filterMode = 3  // ShowByBus
                            meterModel.filterBusId = roomBCard.roomId
                            meterModel.refresh()
                        }
                    }
                }

                Behavior on scale {
                    NumberAnimation {
                        duration: 200
                        easing.type: Easing.OutCubic
                    }
                }

                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: 12
                    spacing: 6

                    RowLayout {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 24
                        spacing: 8

                        Text {
                            text: roomBCard.busIcon
                            font.pixelSize: 16
                        }

                        Text {
                            text: roomBCard.roomName
                            font.pixelSize: 13
                            font.bold: true
                            color: "#2c3e50"
                            Layout.fillWidth: true
                        }

                        Rectangle {
                            width: 45
                            height: 22
                            radius: 3
                            color: roomBCard.onlineMeters > 0 ? "#27ae60" : "#e74c3c"

                            Text {
                                anchors.centerIn: parent
                                text: roomBCard.onlineMeters > 0 ? "运行" : "离线"
                                font.pixelSize: 10
                                font.bold: true
                                color: "white"
                            }
                        }
                    }

                    Rectangle {
                        Layout.fillWidth: true
                        height: 1
                        color: "#ecf0f1"
                    }

                    GridLayout {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        columns: 2
                        rowSpacing: 6
                        columnSpacing: 10

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "在线设备"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: roomBCard.onlineMeters + "/" + roomBCard.totalMeters
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#27ae60"
                                }

                                Text {
                                    text: "台"
                                    font.pixelSize: 10
                                    color: "#95a5a6"
                                }
                            }
                        }

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "在线率"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: roomBCard.totalMeters > 0 ? Math.round((roomBCard.onlineMeters / roomBCard.totalMeters) * 100) : 0
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#3498db"
                                }

                                Text {
                                    text: "%"
                                    font.pixelSize: 10
                                    color: "#95a5a6"
                                }
                            }
                        }

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "总功率"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: (roomBCard.totalPower / 1000).toFixed(1)
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#9b59b6"
                                }

                                Text {
                                    text: "kW"
                                    font.pixelSize: 10
                                    color: "#95a5a6"
                                }
                            }
                        }

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "总电流"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: roomBCard.totalCurrent.toFixed(1)
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#f39c12"
                                }

                                Text {
                                    text: "A"
                                    font.pixelSize: 10
                                    color: "#95a5a6"
                                }
                            }
                        }
                    }
                }

                function updateData() {
                    if (!deviceManager) {
                        console.warn("DashboardPage: deviceManager is null")
                        return
                    }

                    try {
                        roomBCard.onlineMeters = deviceManager.getOnlineCountByBus(roomBCard.roomId)
                        roomBCard.totalPower = deviceManager.getTotalPowerByBus(roomBCard.roomId)
                        roomBCard.totalCurrent = deviceManager.getTotalCurrentByBus(roomBCard.roomId)
                    } catch (e) {
                        console.error("DashboardPage: Error updating room B data:", e)
                    }
                }
            }

            // 配电室C（压缩到140px）
            Rectangle {
                id: roomCCard
                Layout.fillWidth: true
                Layout.preferredHeight: 140

                property string roomName: "配电室C"
                property int roomId: 3
                property string busIcon: "🏗"
                property int totalMeters: 40
                property int startMeterId: 81
                property int endMeterId: 120
                property int onlineMeters: 0
                property real totalPower: 0
                property real totalCurrent: 0

                radius: 8
                color: "white"
                border.width: 2
                border.color: "#3498db"

                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    cursorShape: Qt.PointingHandCursor

                    onEntered: {
                        roomCCard.scale = 1.02
                    }

                    onExited: {
                        roomCCard.scale = 1.0
                    }

                    onClicked: {
                        console.log("Clicked distribution room:", roomCCard.roomName)
                        // 切换到电表列表页并筛选配电室C
                        mainWindow.switchPage("meterlist")
                        // 通过全局属性或信号通知MeterListPage设置筛选条件
                        if (meterModel) {
                            meterModel.filterMode = 3  // ShowByBus
                            meterModel.filterBusId = roomCCard.roomId
                            meterModel.refresh()
                        }
                    }
                }

                Behavior on scale {
                    NumberAnimation {
                        duration: 200
                        easing.type: Easing.OutCubic
                    }
                }

                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: 12
                    spacing: 6

                    RowLayout {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 24
                        spacing: 8

                        Text {
                            text: roomCCard.busIcon
                            font.pixelSize: 16
                        }

                        Text {
                            text: roomCCard.roomName
                            font.pixelSize: 13
                            font.bold: true
                            color: "#2c3e50"
                            Layout.fillWidth: true
                        }

                        Rectangle {
                            width: 45
                            height: 22
                            radius: 3
                            color: roomCCard.onlineMeters > 0 ? "#27ae60" : "#e74c3c"

                            Text {
                                anchors.centerIn: parent
                                text: roomCCard.onlineMeters > 0 ? "运行" : "离线"
                                font.pixelSize: 10
                                font.bold: true
                                color: "white"
                            }
                        }
                    }

                    Rectangle {
                        Layout.fillWidth: true
                        height: 1
                        color: "#ecf0f1"
                    }

                    GridLayout {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        columns: 2
                        rowSpacing: 6
                        columnSpacing: 10

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "在线设备"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: roomCCard.onlineMeters + "/" + roomCCard.totalMeters
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#27ae60"
                                }

                                Text {
                                    text: "台"
                                    font.pixelSize: 12
                                    color: "#95a5a6"
                                }
                            }
                        }

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "在线率"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: roomCCard.totalMeters > 0 ? Math.round((roomCCard.onlineMeters / roomCCard.totalMeters) * 100) : 0
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#3498db"
                                }

                                Text {
                                    text: "%"
                                    font.pixelSize: 12
                                    color: "#95a5a6"
                                }
                            }
                        }

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "总功率"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: (roomCCard.totalPower / 1000).toFixed(1)
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#9b59b6"
                                }

                                Text {
                                    text: "kW"
                                    font.pixelSize: 12
                                    color: "#95a5a6"
                                }
                            }
                        }

                        ColumnLayout {
                            spacing: 3

                            Text {
                                text: "总电流"
                                font.pixelSize: 10
                                color: "#7f8c8d"
                            }

                            RowLayout {
                                spacing: 3

                                Text {
                                    text: roomCCard.totalCurrent.toFixed(1)
                                    font.pixelSize: 16
                                    font.bold: true
                                    color: "#f39c12"
                                }

                                Text {
                                    text: "A"
                                    font.pixelSize: 12
                                    color: "#95a5a6"
                                }
                            }
                        }
                    }
                }

                function updateData() {
                    if (!deviceManager) {
                        console.warn("DashboardPage: deviceManager is null")
                        return
                    }

                    try {
                        roomCCard.onlineMeters = deviceManager.getOnlineCountByBus(roomCCard.roomId)
                        roomCCard.totalPower = deviceManager.getTotalPowerByBus(roomCCard.roomId)
                        roomCCard.totalCurrent = deviceManager.getTotalCurrentByBus(roomCCard.roomId)
                    } catch (e) {
                        console.error("DashboardPage: Error updating room C data:", e)
                    }
                }
            }
        }

        // 系统整体统计（压缩到80px）
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 80
            radius: 6
            color: "white"
            border.width: 1
            border.color: "#bdc3c7"

            RowLayout {
                anchors.fill: parent
                anchors.margins: 12
                spacing: 20

                // 总设备数
                Row {
                    Layout.fillWidth: true
                    spacing: 8
                    Layout.alignment: Qt.AlignHCenter

                    Text {
                        text: "📊"
                        font.pixelSize: 24
                        anchors.verticalCenter: parent.verticalCenter
                    }

                    ColumnLayout {
                        spacing: 3
                        anchors.verticalCenter: parent.verticalCenter

                        Text {
                            text: "总设备数"
                            font.pixelSize: 11
                            color: "#7f8c8d"
                        }

                        Row {
                            spacing: 3

                            Text {
                                text: deviceManager ? deviceManager.totalCount : 0
                                font.pixelSize: 20
                                font.bold: true
                                color: "#3498db"
                            }

                            Text {
                                text: "台"
                                font.pixelSize: 11
                                color: "#95a5a6"
                            }
                        }
                    }
                }

                Rectangle {
                    width: 1
                    height: 50
                    color: "#ecf0f1"
                }

                // 在线设备
                Row {
                    Layout.fillWidth: true
                    spacing: 8
                    Layout.alignment: Qt.AlignHCenter

                    Text {
                        text: "✅"
                        font.pixelSize: 24
                        anchors.verticalCenter: parent.verticalCenter
                    }

                    ColumnLayout {
                        spacing: 3
                        anchors.verticalCenter: parent.verticalCenter

                        Text {
                            text: "在线设备"
                            font.pixelSize: 11
                            color: "#7f8c8d"
                        }

                        Row {
                            spacing: 3

                            Text {
                                text: deviceManager ? deviceManager.onlineCount : 0
                                font.pixelSize: 20
                                font.bold: true
                                color: "#27ae60"
                            }

                            Text {
                                text: "台"
                                font.pixelSize: 11
                                color: "#95a5a6"
                            }
                        }
                    }
                }

                Rectangle {
                    width: 1
                    height: 50
                    color: "#ecf0f1"
                }

                // 离线设备
                Row {
                    Layout.fillWidth: true
                    spacing: 8
                    Layout.alignment: Qt.AlignHCenter

                    Text {
                        text: "❌"
                        font.pixelSize: 24
                        anchors.verticalCenter: parent.verticalCenter
                    }

                    ColumnLayout {
                        spacing: 3
                        anchors.verticalCenter: parent.verticalCenter

                        Text {
                            text: "离线设备"
                            font.pixelSize: 11
                            color: "#7f8c8d"
                        }

                        Row {
                            spacing: 3

                            Text {
                                text: deviceManager ? deviceManager.offlineCount : 0
                                font.pixelSize: 20
                                font.bold: true
                                color: "#e74c3c"
                            }

                            Text {
                                text: "台"
                                font.pixelSize: 11
                                color: "#95a5a6"
                            }
                        }
                    }
                }

                Rectangle {
                    width: 1
                    height: 50
                    color: "#ecf0f1"
                }

                // 在线率
                Row {
                    Layout.fillWidth: true
                    spacing: 8
                    Layout.alignment: Qt.AlignHCenter

                    Text {
                        text: "📈"
                        font.pixelSize: 24
                        anchors.verticalCenter: parent.verticalCenter
                    }

                    ColumnLayout {
                        spacing: 3
                        anchors.verticalCenter: parent.verticalCenter

                        Text {
                            text: "在线率"
                            font.pixelSize: 11
                            color: "#7f8c8d"
                        }

                        Row {
                            spacing: 3

                            Text {
                                text: getOnlineRate()
                                font.pixelSize: 20
                                font.bold: true
                                color: "#9b59b6"
                            }

                            Text {
                                text: "%"
                                font.pixelSize: 11
                                color: "#95a5a6"
                            }
                        }
                    }
                }
            }
        }

        // 最近电表列表（最大化剩余空间）
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            radius: 6
            color: "white"
            border.width: 1
            border.color: "#bdc3c7"

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 12
                spacing: 8

                // 标题栏（压缩）
                RowLayout {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 28

                    Text {
                        text: "💡 电表状态"
                        font.pixelSize: 14
                        font.bold: true
                        color: "#2c3e50"
                        Layout.fillWidth: true
                    }

                    Button {
                        text: "查看全部"
                        font.pixelSize: 11
                        implicitHeight: 26
                        onClicked: {
                            // 切换到电表列表页
                            mainWindow.switchPage("meterlist")
                        }
                    }
                }

                // 电表卡片网格
                ScrollView {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    clip: true
                    contentWidth: availableWidth

                    GridLayout {
                        id: meterGrid
                        width: parent.width
                        columns: Math.max(1, Math.floor(width / 280))
                        rowSpacing: 12
                        columnSpacing: 12

                        Repeater {
                            model: meterModel

                            MeterCard {
                                Layout.fillWidth: true
                                Layout.preferredHeight: 190
                                Layout.minimumWidth: 250
                                Layout.maximumWidth: 400

                                meterId: model.meterId
                                meterName: model.name
                                location: model.location
                                online: model.online
                                ua: model.ua
                                ub: model.ub
                                uc: model.uc
                                ia: model.ia
                                ib: model.ib
                                ic: model.ic
                                averageVoltage: model.averageVoltage
                                averageCurrent: model.averageCurrent
                                totalPower: model.totalPower

                                onClicked: {
                                    console.log("点击电表卡片:", meterId)
                                    // TODO: 打开电表详情页
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // 更新仪表盘数据
    function updateDashboard() {
        if (!deviceManager) {
            console.warn("DashboardPage: deviceManager is null, skipping update")
            return
        }

        try {
            roomACard.updateData()
            roomBCard.updateData()
            roomCCard.updateData()
        } catch (e) {
            console.error("DashboardPage: Error updating dashboard:", e)
        }
    }

    // 计算在线率
    function getOnlineRate() {
        if (!deviceManager || deviceManager.totalCount === 0) {
            return 0
        }
        return Math.round((deviceManager.onlineCount / deviceManager.totalCount) * 100)
    }

    // 组件加载完成
    Component.onCompleted: {
        console.log("DashboardPage loaded")
        updateDashboard()
    }
}
